<!--
 * @Autor: Ruohong Yu
 * @Date: 2021-11-27 16:55:47
 * @LastEditors: Ruohong Yu
 * @LastEditTime: 2021-12-20 12:57:56
 * @Description: 个人中心
 * @FilePath: \mimalld:\桌面\作业\软件工程\前端\front_regit\src\views\Center.vue
-->

<template>
  <div class="center">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
    </el-breadcrumb>

    <el-tabs tab-position="left" style="height: 100%;">
      <el-tab-pane label="基本设置">
        <div class="title">基本设置</div>
        <el-upload
          class="avatar-uploader"
          action="/api/user/image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :data="{}"
          :before-upload="beforeAvatarUpload"
          style="display: inline-block;width: 300px"
        >
          <div v-if="tx" class="avatar">
            <img :src="tx">
          </div>
          <div class="xg">修改头像</div>

        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <div class="simple">
          <div>
            <span>学工号</span>
            <el-input
              v-model="usernumber"
              :placeholder="usernumber"
              :disabled="true"
            />
          </div>

          <div>
            <span>用户名</span>
            <el-input
              v-model="username"
              :placeholder="username"
              :disabled="nameable"
            />
            <el-button type="primary" icon="el-icon-edit" circle @click="nameedit" />
            <el-button type="success" icon="el-icon-check" circle @click="usernameedit" />
          </div>

          <div>
            <span>邮箱</span>
            <el-input
              v-model="useremail"
              :placeholder="useremail"
              :disabled="emailable"
            />
            <el-button type="primary" icon="el-icon-edit" circle @click="emailedit" />
            <el-button type="success" icon="el-icon-check" circle @click="useremailedit" />
          </div>

          <div>
            <span>手机号</span>
            <el-input
              v-model="usermobile"
              :placeholder="usermobile"
              :disabled="mobileable"
            />
            <el-button type="primary" icon="el-icon-edit" circle @click="mobileedit" />
            <el-button type="success" icon="el-icon-check" circle @click="usermobileedit" />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="安全设置">
        <div class="anquan">
          <div class="title">
            安全设置
          </div>
          <el-form ref="ruleForm" :model="ruleForm" status-icon :rules="rules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="原密码" prop="oripass">
              <el-input v-model="ruleForm.oripass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="新密码" prop="pass">
              <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

      </el-tab-pane>
      <el-tab-pane label="点击有惊喜">
        <div class="title">
          管理员注册
        </div>
        <!--非管理员填写邀请码-->
        <el-form v-if="userRoleId != 0" status-icon label-width="100px" class="demo-ruleForm">
          <el-form-item label="管理员邀请码">
            <el-input v-model="inviteCode" style="width:400px;margin-top:20px" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitInviteCode()">提交</el-button>
          </el-form-item>
        </el-form>
        <!--管理员生成邀请码-->
        <el-button v-else type="primary" style="margin-top:20px" @click="MyinviteCode()">点击生成邀请码</el-button>
        <!-- <p>{{ adminCode }}</p> -->
        <!--邀请码弹框-->
        <el-dialog title="邀请码" :visible.sync="setDialogVisible" width="50%">
          <div>
            {{ adminCode }}
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setDialogVisible = false">关 闭</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="新消息通知">定时任务补偿</el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
// import axios from 'axios'
import crypto from '../crypto/crypto'
export default {
  name: 'Center',
  data() {
    /**
     * @description: 表单验证
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    var checkori = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入原密码'))
      } else {
        callback()
      }
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      username: '',
      useremail: '',
      usermobile: '',
      usernumber: '',
      userid: '',
      mobileable: true,
      nameable: true,
      emailable: true,
      tx: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      ruleForm: {
        pass: '',
        checkPass: '',
        oripass: ''
      },
      rules: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        oripass: [
          { validator: checkori, trigger: 'blur' }
        ]
      },
      userId: '',
      userRoleId: '',
      setDialogVisible: false,
      inviteCode: '',
      adminCode: ''
    }
  },
  created: function() {
    this.getUserInfo()
    this.init()
  },
  methods: {
    /**
     * @description: 提交表单
     * @param {*} formName
     * @return {*}
     * @author: Ruohong Yu
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios.post('user/updatePwd', {
            newPassword: this.ruleForm.checkPass,
            originalPassword: this.ruleForm.oripass,
            userId: this.userid
          })
            .then(res => {
              // console.log(res)
            })
            .catch(err => {
              console.error(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitInviteCode() {
      this.axios.get('user/becomeAdmin', { params: { userId: this.$store.getters.getuserId, code: this.inviteCode }})
        .then(res => {
          this.readmessage()
        })
        .catch(err => {
          console.error(err)
        })
    },
    readmessage() {
      this.$confirm('是否立即重新登录?', '提示', {
        confirmButtonText: '立即退出',
        cancelButtonText: '稍后退出',
        type: 'warning'
      }).then(() => {
        this.logout()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    getUserInfo() {
      this.axios.get('/user/')
        .then((res) => {
          this.userRoleId = res.data.data.roleId
        })
        .catch(err => {
          console.error(err)
        })
    },
    inviteDialog() {
      this.axios.get('/user/generateSuperCode').then((response) => {
        this.inviteCode = response.data.data
      }).catch(error => {
        console.log(error)
      })
      this.setDialogVisible = true
    },
    MyinviteCode() {
      this.axios.get('/user/generateSuperCode', { params: { userId: this.$store.getters.getuserId }}).then((response) => {
        this.adminCode = response.data.data
      }).catch(error => {
        console.log(error)
      })
      this.setDialogVisible = true
    },
    logout() {
      this.axios
        .get('user/logout')
        .then(() => {
          this.$message.info('退出成功')
        })
        .catch((error) => {
          console.log(error)
        })
      // 清空token
      window.sessionStorage.clear()
      this.$router.push('/')
      window.location.reload()
    },
    /**
     * @description: 重置表单
     * @param {*} formName
     * @return {*}
     * @author: Ruohong Yu
     */
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    /**
     * @description: 初始化
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    init() {
      this.username = crypto.get(this.$store.getters.getusername)
      this.useremail = crypto.get(this.$store.getters.getuserEmail)
      this.usermobile = crypto.get(this.$store.getters.getuserMobile)
      this.userid = this.$store.getters.getuserId
      this.usernumber = crypto.get(this.$store.getters.getuserNumber)
      this.axios.get('/user/getImage', { params: { userId: this.userid }})
        .then((res) => {
          this.tx = res.data.data
        })
        .catch(err => {
          console.error(err)
        })
    },

    /**
     * @description: 用户名编辑按钮
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    nameedit() {
      this.nameable = false
    },

    /**
     * @description: 用户名编辑
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    usernameedit() {
      this.axios.post('user/updateBasicInfo', {
        userEmail: this.useremail,
        userId: this.userid,
        userMobile: this.usermobile,
        username: this.username
      })
        .then((res) => {
          this.$message.success('修改成功')
          this.username = res.data.data.username
          this.nameable = true
        })
        .catch(() => {
          this.$message.success('修改失败')
        })
    },

    /**
     * @description: 邮箱编辑按钮
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    emailedit() {
      this.emailable = false
    },

    /**
     * @description: 邮箱编辑
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    useremailedit() {
      this.axios.post('user/updateBasicInfo', {
        userEmail: this.useremail,
        userId: this.userid,
        userMobile: this.usermobile,
        username: this.username
      })
        .then((res) => {
          this.$message.success('修改成功')
          this.useremail = res.data.data.userEmail
          this.emailable = true
        })
        .catch(() => {
          this.$message.error('修改失败')
        })
    },

    /**
     * @description: 手机号编辑按钮
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    mobileedit() {
      this.mobileable = false
    },

    /**
     * @description: 手机号编辑
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    usermobileedit() {
      this.axios.post('user/updateBasicInfo', {
        userEmail: this.useremail,
        userId: this.userid,
        userMobile: this.usermobile,
        username: this.username
      })
        .then((res) => {
          this.$message.success('修改成功')
          this.useremobile = res.data.data.usereMobile
          this.emailable = true
        })
        .catch(() => {
          this.$message.success('修改失败')
        })
    },

    /**
     * @description: 获取用户头像
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    handleAvatarSuccess() {
      this.axios.get('/user/getImage', { params: { userId: this.userid }})
        .then((res) => {
          this.tx = res.data.data
        })
        .catch(err => {
          console.error(err)
        })
    },

    /**
     * @description: 头像上传规定
     * @param {*} file
     * @return {*}
     * @author: Ruohong Yu
     */
    beforeAvatarUpload(file) {
    // const isJPG = file.type === 'image/jpeg'
    // const isLt2M = file.size / 1024 / 1024 < 2

    // if (!isJPG) {
    //   this.$message.error('上传头像图片只能是 JPG 格式!')
    // }
    // if (!isLt2M) {
    //   this.$message.error('上传头像图片大小不能超过 2MB!')
    // }
    // return isJPG && isLt2M
    }
  }

  // getUserInfo() {
  //   this.axios.get('/user/')
  //     .then((res) => {
  //       this.userId = res.data.data.userId
  //       this.userRoleId = res.data.data.roleId
  //     })
  //     .catch(err => {
  //       console.error(err)
  //     })
  // },
  // inviteDialog() {
  //   this.axios.get('/user/generateSuperCode').then((response) => {
  //     this.inviteCode = response.data.data
  //   }).catch(error => {
  //     console.log(error)
  //   })
  //   this.setDialogVisible = true
  // },
  // MyinviteCode() {
  //   this.axios.get('/user/generateSuperCode', { params: { userId: this.$store.getters.getuserId }}).then((response) => {
  //     this.adminCode = response.data.data
  //   }).catch(error => {
  //     console.log(error)
  //   })
  // }
}

</script>
<style lang="less">
.title{
  font-size: 15px;
  font-weight: 500;
}
.avatar{
  width: 120px;
  height: 120px;
  margin-left: 470px;
  border-radius: 49%;
  overflow: hidden;
  border: 1px solid rgb(168, 168, 168);
  img{
    width: 120px;
    height: 120px;
  }
}
.anquan{
  .el-form{
    margin-top: 50px;
    width: 500px;
    margin-left: 250px;
    .el-form-item__label{
      font-weight: 200;
    }
  }
}
.xg{
  margin-top: 5px;
  font-size: 13px;
  font-weight: 200;
  cursor: pointer;
  margin-left: 470px;
  color: #1560ac;
}
.center{
  background-color: #f0f2f59d;
  border-radius: 10px;
  padding: 10px;
}
.el-tabs__item.is-active {
  background-color: #c1dffd8a;
}
.el-tabs__item{
  font-size: 15px ;
  font-weight: 200 ;
  height: 50px ;
  line-height: 50px ;
}
.simple{
  margin-left: 250px;
  margin-bottom: 50px;
  div{
    height: 50px;
    margin: 10px;
    span{
      display: inline-block;
      font-size: 15px;
      font-weight: 200;
      width: 70px;
      height: 50px;
      line-height: 50px;
    }
    .el-input{
      width: 400px;
    }
  }
}

</style>
